<?php

/**
 * Description of DataFilter
 *
 * @author bonfiglio
 * @todo Commenter !!!
 */
class DataFilter {

    public $filter = null;
    private $valid = true;
    public $validate = null;
    public $sanitize = null;
    public $options = null;
    public $default = null;
    public $required = null;
    public $value = null;
    public $values = null;

    public function __construct($value = null, $attributs = array()) {

        $this->filter = isset($attributs['filter']) ? $attributs['filter'] : FILTER_DEFAULT;

        $this->validate = isset($attributs['validate']) ? $attributs['validate'] : false;

        $this->sanitize = isset($attributs['sanitize']) ? $attributs['sanitize'] : false;

        $this->options = isset($attributs['options']) ? $attributs['options'] : array();

        $this->required = isset($attributs['required']) ? (boolean) $attributs['required'] : false;

        $this->values = isset($attributs['values']) ? $attributs['values'] : array();

        //Filtrage
        if (is_null($value)) {
            $this->valid = false;
        } elseif ($this->validate) {
            $this->valid = filter_var($value, $this->validate, $this->options);
        }

        if ($this->valid) {
            if ($this->filter) {
                $this->valid = filter_var($value, $this->filter, $this->options);
            }
            if ($this->valid && $this->sanitize) {
                $this->value = $this->valid = filter_var($value, $this->sanitize, $this->options);
            }else{
                $this->value = $this->valid;
            }
        }
    }

    public function getValue() {
        if (!$this->valid) {
            return $this->getDefaultValue($this->value);
        } else {
            return $this->value;
        }
    }

    public function isValid() {
        return $this->valid;
    }

    public function isRequired() {
        return $this->required;
    }

    public function hasDefaultValue() {
        return isset($this->options['default']);
    }

    public function getDefaultValue($value) {
        if ($this->hasDefaultValue()) {
            $value = $this->options['default'];
        }
        return $value;
    }

}

?>
